<template>
  <Layout>
    <div class="finance-container">
      <!-- 顶部统计卡片 -->
      <SummaryCards :summary-data="summaryData" />

      <!-- 主要内容区域 -->
      <div class="main-content">
        <!-- 左侧：理财产品列表 -->
        <ProductList
          :products="products"
          :loading="productsLoading"
          :filters="filters"
          :pagination="pagination"
          @refresh="loadProducts"
          @filter-change="handleFilterChange"
          @page-change="handlePageChange"
          @size-change="handleSizeChange"
          @product-detail="showProductDetail"
          @purchase="showPurchaseDialog"
        />

        <!-- 右侧：我的投资 -->
        <InvestmentList
          :investments="myInvestments"
          :loading="investmentsLoading"
          :pagination="investmentPagination"
          @refresh="loadMyInvestments"
          @page-change="handleInvestmentPageChange"
          @size-change="handleInvestmentSizeChange"
          @investment-detail="showInvestmentDetail"
        />
      </div>

      <!-- 购买弹窗 -->
      <PurchaseDialog
        :visible="purchaseDialog.visible"
        :product="purchaseDialog.product"
        :user-balance="userBalance"
      
        @update:visible="value => purchaseDialog.visible = value"
        @confirm="handlePurchaseConfirm"
      />

      <!-- 产品详情弹窗 -->
      <ProductDetailDialog
        :visible="productDetailDialog.visible"
        :product="productDetailDialog.product"
        @update:visible="value => productDetailDialog.visible = value"
        @purchase="showPurchaseDialogFromDetail"
      />

      <!-- 投资详情弹窗 -->
      <InvestmentDetailDialog
        :visible="investmentDetailDialog.visible"
        :data="investmentDetailDialog.data"
        @update:visible="value => investmentDetailDialog.visible = value"
      />
    </div>
  </Layout>
</template>

<script setup name="FinanceView">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import Layout from '@/components/layout/Layout.vue';
import SummaryCards from '@/components/finance/SummaryCards.vue';
import ProductList from '@/components/finance/ProductList.vue';
import InvestmentList from '@/components/finance/InvestmentList.vue';
import PurchaseDialog from '@/components/finance/PurchaseDialog.vue';
import ProductDetailDialog from '@/components/finance/ProductDetailDialog.vue';
import InvestmentDetailDialog from '@/components/finance/InvestmentDetailDialog.vue';
import { 
  getProductList, 
  getInvestmentOrderList, 
  getInvestmentSummary, 
  purchaseProduct,
  getProductDetail,
  getInvestmentOrderDetail
} from '@/api/finance';
import { getAccountBalance } from '@/api/account';

// 响应式数据
const summaryData = ref({
  totalInvestment: 0,
  currentValue: 0,
  totalProfit: 0,
  profitRate: 0,
  accumulatedEarnings: 0
});

const products = ref([]);
const productsLoading = ref(false);
const myInvestments = ref([]);
const investmentsLoading = ref(false);
const userBalance = ref(0);

// 筛选条件
const filters = reactive({
  riskLevel: '',
  duration: ''
});

// 分页
const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
});

const investmentPagination = reactive({
  page: 1,
  size: 5,
  total: 0
});

// 购买弹窗
const purchaseDialog = reactive({
  visible: false,
  product: null
});



// 产品详情弹窗
const productDetailDialog = reactive({
  visible: false,
  product: null
});

// 投资详情弹窗
const investmentDetailDialog = reactive({
  visible: false,
  data: null
});

// 计算预期收益（暂未使用，保留用于后续功能扩展）
// const expectedProfit = computed(() => {
//   if (!purchaseDialog.product) return 0;
//   // 应该动态计算收益，但这里返回0，让购买组件内部计算
//   return 0;
// });

// 处理子组件事件
const handleFilterChange = ({ key, value }) => {
  filters[key] = value;
  pagination.page = 1; // 重置分页
  loadProducts();
};

const handlePageChange = (page) => {
  pagination.page = page;
  loadProducts();
};

const handleSizeChange = (size) => {
  pagination.size = size;
  pagination.page = 1; // 重置分页
  loadProducts();
};

const handleInvestmentPageChange = (page) => {
  investmentPagination.page = page;
  loadMyInvestments();
};

const handleInvestmentSizeChange = (size) => {
  investmentPagination.size = size;
  investmentPagination.page = 1; // 重置分页
  loadMyInvestments();
};



// 处理购买确认
const handlePurchaseConfirm = async (data) => {
  try {
    console.log('开始购买，数据：', data);
    const response = await purchaseProduct(data);
    console.log('购买响应：', response);
    
    ElMessage.success('购买成功');
    purchaseDialog.visible = false;
    
    // 刷新数据
    await Promise.all([
      loadSummary(),
      loadMyInvestments(),
      loadUserBalance(),
      loadProducts() // 也要刷新产品列表，显示最新的销售进度
    ]);
    
  } catch (error) {
    console.error('购买失败详细信息：', error);
    const errorMessage = error.response?.data?.message || error.message || '购买失败';
    ElMessage.error(errorMessage);
  }
};

// 数据加载方法
const loadSummary = async () => {
  try {
    const response = await getInvestmentSummary();
    summaryData.value = response.data || {
      totalInvestment: 0,
      currentValue: 0,
      totalProfit: 0,
      profitRate: 0,
      accumulatedEarnings: 0
    };
  } catch (error) {
    console.error('加载投资统计失败：', error);
  }
};

const loadProducts = async () => {
  productsLoading.value = true;
  try {
    const params = {
      page: pagination.page,
      size: pagination.size,
      riskLevel: filters.riskLevel || undefined,
      minDuration: filters.duration?.min || undefined,
      maxDuration: filters.duration?.max || undefined,
      status: 1 // 只显示在售产品
    };
    
    // 清理undefined参数
    Object.keys(params).forEach(key => {
      if (params[key] === undefined) {
        delete params[key];
      }
    });
    
    const response = await getProductList(params);
    products.value = response.data.list || [];
    pagination.total = response.data.total || 0;
  } catch (error) {
    console.error('加载理财产品失败：', error);
    ElMessage.error('加载理财产品失败');
  } finally {
    productsLoading.value = false;
  }
};

const loadMyInvestments = async () => {
  investmentsLoading.value = true;
  try {
    const params = {
      page: investmentPagination.page,
      size: investmentPagination.size
    };
    
    const response = await getInvestmentOrderList(params);
    console.log('投资列表数据:', response.data);
    
    if (response.data && response.data.list) {
      myInvestments.value = response.data.list || [];
      investmentPagination.total = response.data.total || 0;
    } else {
      console.warn('投资列表数据格式不正确:', response.data);
      myInvestments.value = [];
      investmentPagination.total = 0;
    }
  } catch (error) {
    console.error('加载我的投资失败：', error);
    ElMessage.error('加载我的投资失败');
    myInvestments.value = [];
  } finally {
    investmentsLoading.value = false;
  }
};

const loadUserBalance = async () => {
  try {
    const response = await getAccountBalance();
    userBalance.value = response.data.balance || 0;
  } catch (error) {
    console.error('加载账户余额失败：', error);
  }
};

// 弹窗操作方法
const showProductDetail = async (product) => {
  try {
    const response = await getProductDetail(product.id);
    productDetailDialog.product = response.data;
    productDetailDialog.visible = true;
  } catch (error) {
    console.error('加载产品详情失败：', error);
    ElMessage.error('加载产品详情失败');
  }
};

const showPurchaseDialog = (product) => {
  purchaseDialog.product = product;
  purchaseDialog.visible = true;
  // 加载用户余额
  loadUserBalance();
};

const showPurchaseDialogFromDetail = () => {
  productDetailDialog.visible = false;
  showPurchaseDialog(productDetailDialog.product);
};

const showInvestmentDetail = async (investment) => {
  try {
    const response = await getInvestmentOrderDetail(investment.id);
    // 检查响应数据是否有效
    if (response.data) {
      investmentDetailDialog.data = response.data;
      investmentDetailDialog.visible = true;
    } else {
      console.error('投资详情数据为空');
      ElMessage.warning('暂无投资详情数据');
    }
  } catch (error) {
    console.error('加载投资详情失败：', error);
    ElMessage.error('加载投资详情失败');
  }
};



// 生命周期
onMounted(() => {
  loadSummary();
  loadProducts();
  loadMyInvestments();
});
</script>

<style scoped>
.finance-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

/* 主内容区域 */
.main-content {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .main-content {
    grid-template-columns: 1fr;
  }
}
</style>
